package top.ljlgithub.api.shiro.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import top.ljlgithub.api.bean.Manager;
import top.ljlgithub.api.jwt.JwtToken;
import top.ljlgithub.api.jwt.JwtUtils;
import top.ljlgithub.api.mapper.ManagerMapper;

import java.security.Security;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
 * @ClassName
 * @Description TODO
 * @Author L1470
 * @Date 2021/4/24 13:38
 * @Version 1.0
 **/


/**
 * JwtRealm 只负责校验 JwtToken
 */

public class JwtRealm extends AuthorizingRealm {
    @Autowired
    ManagerMapper managerMapper;

    /**
     * 限定这个 Realm 只处理我们自定义的 JwtToken
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 此处的 SimpleAuthenticationInfo 可返回任意值，密码校验时不会用到它
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authenticationToken;
        if (jwtToken.getPrincipal() == null) {
            throw new AccountException("JWT token参数异常！");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(jwtToken.getPrincipal(),jwtToken.getCredentials(),getName());
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //给用户添加权限
        String psIds = managerMapper.getPsIds(principals.getPrimaryPrincipal().toString());
        //2.创建一个set集合用于存放该用户的所有权限
        HashSet<String> permissions = new HashSet<>();
        //3.将ps_ids变成整数数组
        String[] split = psIds.split(",");
        for (String s : split) {
            int id = Integer.parseInt(s);
            String permission = managerMapper.getPermissionById(id);
            if (permission != null && !permission.equals("")) {
                permissions.add(permission);
            }
        }
        //4.打印所有权限
        //System.out.println(permissions);
        //5.设置用户权限
        info.setStringPermissions(permissions);
        return info;
    }

}
